<?php

/**
 * Created by PhpStorm.
 * User: Lomon
 * Date: 2020/12/03
 * 定时执行 每个月1号分配上一个月的团队育成佣金
 * 默认 0 8 1 * * 每月1号凌晨8点
 *
 * 用户A的团队成员B：用户A和B都是玩客，B本月的总收入是α元，A次月获得团队育成佣金收益=αX10%
    用户A和B都是玩主，B本月的总收入是β元，A次月获得团队育成佣金收益=βX20%
    用户A和B都是玩家，B本月的总收入是γ元，A次月获得团队育成佣金收益=γX30%

 */
namespace app\admin\command;

use addons\shopro\model\UserWalletLog;
use app\common\model\RetailConfig;
use app\common\model\RetailReward;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Exception;

use app\common\model\RetailUser;
use think\Db;

class RewardYuchen extends Command
{
    protected function configure()
    {
        $this->setName('RewardYuchen')->setDescription('每个月1号分配上一个月的团队育成佣金');
    }
    protected function execute(Input $input, Output $output)
    {
        $WalletModel = new UserWalletLog();

        //上个月1号
        $lastMonth = strtotime(date('Y-m-01',strtotime("last month")));
        //这个月1号
        $thisMonth = strtotime(date('Y-m-01'));

        try{

            //SELECT parent.*,child.uid as cuid,child.pid as child_pid from fa_retail_user parent
            //join fa_retail_user child on child.pid = parent.uid and child.level=4
            //where parent.level=4
            
            //分配给直属上级X元,retail_config.under_wanjia,根据B的等级来决定给多少推荐奖励
            $retailConfigModel = new RetailConfig();
            $conf   = $retailConfigModel->getRecommendConfig("team");

            //大于粉丝的会员
            $users = db('retail_user')->where(['level'=>['gt',RetailUser::LEVEL_FENS],'status'=>RetailUser::STATUS_ENABLE])->column('uid,level,total_income');

            $type = "sale_reward_team";
            foreach ($users as $k=>$u){
                //判断此用户是否已经分过上个月的团队收入了
                $w = ['user_id'=>$k,
                    'type'=>$type,
                    'wallet_type'=>'money',
                    'create_time'=>['gt',$thisMonth]
                ];
                $log = db('user_wallet_log')->where($w)->find;

                if($log){
                    continue;
                }

                $u['id'] = $k;
                //统计团队成员
                $teamIds = model('retail_user')->teamPersonList($u,true);

                //统计团队销售收入总额,wallet_log.type=sale_reward
                $team_w = [
                    'user_id'=>['in',$teamIds],
                    'create_time'=>['between',"{$lastMonth},{$thisMonth}"]
                ];
                $wallet_sum = db('user_wallet_log')->where($team_w)
                    ->sum("wallet");

                //开始团队销售额佣金
                if($wallet_sum && !empty($conf[$u['level']])){
                    $commission = $wallet_sum * $conf[$u['level']];

                    Db::startTrans();
                    try{

                        db('user')->where(['id'=>$k])->setInc('money',$commission);

                        $userWallet = clone $WalletModel;
                        $userWallet->doAdd($u, $commission, $type, 0, "money", 1);

                        Db::commit();
                    }catch (\Exception $e){
                        Db::rollback();
                        \think\log::error("用户:{$u['id']}的团队分配任务失败:".$e->getMessage());
                    }
                }
            }
        }catch (\Exception $e){
            \think\log::error("团队分成分配任务失败:".$e->getMessage());
            exit;
        }

        echo "分配成功";exit;
    }
}